<?php

namespace App\Http\Api\Controllers;

use App\Http\Api\Services\OAuth as OAuthService;
use App\Models\Connect as ConnectModel;
use Phalcon\Http\Response as HttpResponse;

/**
 * @RoutePrefix("/api/oauth")
 */
class OAuthController extends Controller
{

    /**
     * @Post("/qq/login", name="api.oauth.qq_login")
     */
    public function qqAction(): HttpResponse
    {
        return $this->loginByProvider(ConnectModel::PROVIDER_QQ);


    }

    /**
     * @Post("/weixin/login", name="api.oauth.weixin_login")
     */
    public function weixinAction(): HttpResponse
    {
        return $this->loginByProvider(ConnectModel::PROVIDER_WEIXIN);
    }

    /**
     * @Post("/weibo/login", name="api.oauth.weibo_login")
     */
    public function weiboAction(): HttpResponse
    {
        return $this->loginByProvider(ConnectModel::PROVIDER_WEIBO);
    }

    /**
     * @Post("/bind/login", name="api.oauth.bind_login")
     */
    public function bindLoginAction(): HttpResponse
    {
        [
            'open_user' => $openUser,
            'account' => $account,
            'password' => $password,

        ] = $this->request->getPost();

        $connectService = new OAuthService();

        $token = $connectService->bindLogin($openUser, $account, $password);

        return $this->jsonSuccess(['token' => $token]);
    }

    /**
     * @Post("/bind/register", name="api.oauth.bind_register")
     */
    public function bindRegisterAction(): HttpResponse
    {
        [
            'open_user' => $openUser,

        ] = $this->request->getPost();

        $connectService = new OAuthService();

        $token = $connectService->bindRegister($openUser);

        return $this->jsonSuccess(['token' => $token]);
    }

    /**
     * @Post("/bind/current", name="api.oauth.bind_current")
     */
    public function bindCurrentAction(): HttpResponse
    {
        [
            'open_user' => $openUser,

        ] = $this->request->getPost();

        $connectService = new OAuthService();

        $connectService->bindCurrent($openUser);

        return $this->jsonSuccess();
    }


    protected function loginByProvider(int $provider): HttpResponse
    {
        [
            'code' => $code,

        ] = $this->request->getPost();


        $oauthService = new OAuthService();

        $openUser = $oauthService->getOpenUserInfo($provider, $code);

        $connectRelation = $oauthService->getConnectRelation($openUser['id'], $openUser['provider']);

        $token = '';

        if ($connectRelation) {
            $token = $oauthService->login($connectRelation);
        }

        return $this->jsonSuccess([
            'token' => $token,
            'open_user' => $openUser,
        ]);
    }

}
